package com.fsi.server;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.fsi.client.Customer;
import com.fsi.client.Shuttle;

public class PhotoDAO {
	private final Logger log = Logger.getLogger(PhotoDAO.class.getName());
	private final static PhotoDAO instance = new PhotoDAO();
	private static final int SETMAINON = 0;
	private static final int SETOTHERMAINOFF = 1;
	private static final int SETOTHERMAINON = 2;

	public static PhotoDAO get() {
		return instance;
	}

	public Photo getUserPhoto(String nick) {
		log.info("getUserPhoto: " + nick);
		Photo result = null;

		if (nick != null) {
			PersistenceManager pm = PMF.get().getPersistenceManager();

			try {
				result = pm.getObjectById(Photo.class, nick);
			} catch (javax.jdo.JDOObjectNotFoundException e) {
				result = null;
			}
		}
		return result;
	}

	public String updatePhoto(String fileName, byte[] content,
			String contentType, String customerID, boolean isMainImage,
			String title) {

		// make screenName unique in case customer selects diff images with same
		// filename
		Date now = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String photoID = format.format(now) + fileName;

		if (title == "")
			title = photoID;

		log.info("updatePhoto (WITH BYTES): " + photoID + ", " + contentType
				+ ", " + fileName + " length: " + content.length);
		String debugStr = null;

		PersistenceManager pm = PMF.get().getPersistenceManager();
		Photo result = null;

		try {
			result = pm.getObjectById(Photo.class, photoID);
		} catch (javax.jdo.JDOObjectNotFoundException e) {
			result = null;
		}

		if (result == null) {
			log.info("no image found. creating new one");
			debugStr = "no image found. creating new one";
			result = new Photo(photoID, fileName, contentType, content,
					customerID, isMainImage, title);

			try {
				pm.makePersistent(result);
			} finally {
				pm.close();
			}

		} else {
			log.info("update existing image");
			debugStr = "update existing image";
			result.setIsMainImage(isMainImage);

			pm.close();
		}

		updateIsMainImage(customerID, photoID, true, SETOTHERMAINOFF);

		updateCustomer(customerID, photoID);

		return debugStr;
	}

	private void updateCustomer(String customerID, String photoID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.currentTransaction().begin();

			// We don't have a reference to the selected Product.
			// So we have to look it up first,
			Customer customer = pm.getObjectById(Customer.class, customerID);
			customer.setPhotoID(photoID);

			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}
	}

	private void updateIsMainImage(String customerID, String photoID,
			boolean setTrue, int type) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String queryStr = "";

		try {
			switch (type) {
			case SETMAINON:
				queryStr = "select from " + Photo.class.getName()
						+ " where customerID == '" + customerID + "'"
						+ " && isMainImage == true" + " && photoID != '"
						+ photoID + "'";
				break;
			case SETOTHERMAINOFF:
				queryStr = "select from " + Photo.class.getName()
						+ " where customerID == '" + customerID + "'"
						+ " && isMainImage == true" + " && photoID == '"
						+ photoID + "'";
				break;
			case SETOTHERMAINON:
				queryStr = "select from " + Photo.class.getName()
						+ " where customerID == '" + customerID + "'"
						+ " && isMainImage == false" + " && photoID == '"
						+ photoID + "'";
				break;

			}
			System.out.println(queryStr);
			try {
				List<Photo> photos = (List<Photo>) pm.newQuery(queryStr)
						.execute();

				for (Photo p : photos) {
					p.setIsMainImage(setTrue);
					pm.makePersistent(p);
				}
			} catch (Exception e) {
				System.err.println(e.getMessage());
			}
		} finally {
			pm.close();
		}
	}

	public List<Shuttle> getPhotos(String customerID) {
		List<Shuttle> result = new ArrayList<Shuttle>();
		List<Photo> qr = null;
		Shuttle sh;

		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			String query = "select from " + Photo.class.getName()
					+ " where customerID == '" + customerID + "'";
			qr = (List<Photo>) pm.newQuery(query).execute();
			qr.size();
			for (Photo p : qr) {
				sh = new Shuttle(p.getPhotoID(), p.getTitle());
				result.add(sh);
			}
		} finally {
			pm.close();
		}
		return result;
	}

	public void deletePhoto(String customerID, String photoID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.currentTransaction().begin();

			// We don't have a reference to the selected Product.
			// So we have to look it up first,
			Photo photo = pm.getObjectById(Photo.class, photoID);
			pm.deletePersistent(photo);

			pm.currentTransaction().commit();
		} catch (Exception ex) {
			pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
		} finally {
			pm.close();
		}

	}
}
// public void updatePicture(String screenName, String content,
// String contentType, String fileName, String customerID,
// boolean isMainImage) {
// log.info("updatePicture: " + screenName + ", " + contentType + ", "
// + fileName + " length: " + content.length());
//
// PersistenceManager pm = PMF.get().getPersistenceManager();
// Photo result = null;
// try {
// result = pm.getObjectById(Photo.class, screenName);
// } catch (javax.jdo.JDOObjectNotFoundException e) {
// result = null;
// }
//
// if (result == null) {
// log.info("no image found. creating new one");
// result = new Photo(screenName, fileName, contentType, content,
// customerID, isMainImage);
//
// try {
// pm.makePersistent(result);
// } finally {
// pm.close();
// }
//
// } else {
// log.info("update existing image");
// result.setContentType(contentType);
// result.setFileName(fileName);
// try {
// result.setContent(new Blob(content.getBytes("UTF-8")));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// pm.close();
// }
//
// }
